/*
 * @Author: i@douxuefeng.cn
 * @Date: 2021-12-23 12:15:22
 * @LastEditTime: 2021-12-23 18:58:39
 * @LastEditors: i@douxuefeng.cn
 * @Description: 将聊天记录保存在文件里
 * @FilePath: \go-im\ws\msg_log.go
 */

package ws

import (
	"encoding/json"
	"fmt"

	"gitee.com/douxuefeng/go-im/cache"
	"gitee.com/douxuefeng/go-im/params"
)

type log struct {
	room string
}

func NewLog(room string) *log {
	return &log{room: room}
}

func (l *log) write(msg params.LogMsg) {
	c := cache.RedisPool.Get()
	defer c.Close()
	data, _ := json.Marshal(msg)
	c.Do("lpush", "room_"+l.room, data)
}

func (l *log) read() []params.LogMsg {
	c := cache.RedisPool.Get()
	defer c.Close()
	value, err := c.Do("lrange", "room_"+l.room, 0, 4)
	if err != nil {
		fmt.Println(err)
	}
	var logs []params.LogMsg
	for _, v := range value.([]interface{}) {
		var log params.LogMsg
		json.Unmarshal(v.([]byte), &log)
		logs = append(logs, log)
	}
	return logs
}
